from django.shortcuts import render,redirect, get_object_or_404
from django.http import HttpResponseRedirect,Http404,HttpResponse
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.core.paginator import Paginator
from .models import Topic,Entry,Friendship
from .forms import TopicForm,EntryForm
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from .serializers import FriendshipSerializer
from django.contrib.auth.models import User
from ratelimit.decorators import RateLimitDecorator
# Create your views here.
ratelimit = RateLimitDecorator(calls=15,period=60, raise_on_limit=False)
@ratelimit  # block=False：不拦截，注入 request.limited
def custom_response_view(request):
    if getattr(request, 'limited', False):  # 自定义判断逻辑
        return HttpResponse("请求过于频繁，请稍后再试", status=429)
    return HttpResponse("正常响应")  # 未超限则执行原逻辑
def index(request):
    """学习笔记的主页"""
    return render(request,'learn_app/index.html')

def topics(request):
    """显示主题"""
    public_topics = []
    private_topics = []
    if request.user.is_authenticated:
        user_topics=Topic.objects.filter(owner=request.user).order_by('-date_added')
        public_topics = user_topics.filter(public=True)  
        private_topics = user_topics.filter(public=False)
        others_public_topics=Topic.objects.filter(public=True).exclude(owner=request.user).order_by('-date_added').select_related('owner')
        paginator = Paginator(others_public_topics, 10)
        page_obj = paginator.get_page(request.GET.get('page'))
    else:
        others_public_topics=Topic.objects.filter(public=True).order_by('-date_added').select_related('owner')
        paginator = Paginator(others_public_topics, 10)
        page_obj = paginator.get_page(request.GET.get('page'))
    context={'public_topics':public_topics,'private_topics':private_topics,'others_public_topics':page_obj}
    return render(request,'learn_app/topics.html',context)

def topic(request,topic_id):
    """显示主题详细内容"""
    topic = get_object_or_404(Topic, id=topic_id)
    if topic.owner != request.user and not topic.public:
        raise Http404
    entries=topic.entry_set.order_by('-date_added')#降序排序
    context={'topic':topic,'entries':entries}
    return render(request,'learn_app/topic.html',context)

@ratelimit
@login_required
def new_topic(request):
    """添加新主题"""
    if request.method != 'POST':
        form = TopicForm()
    else:
        form = TopicForm(request.POST)
        if form.is_valid():
            new_topic = form.save(commit=False)
            new_topic.owner = request.user 
            new_topic.save()
            return HttpResponseRedirect(reverse('learn_app:topics'))
    context={'form':form}
    return render(request,'learn_app/new_topic.html',context)

@ratelimit
@login_required 
def new_entry(request,topic_id):
    """添加新目录"""
    topic = Topic.objects.get(id=topic_id)
    if topic.owner != request.user:
        raise Http404
    if request.method != 'POST':
        form = EntryForm()
    else:
        form = EntryForm(request.POST)
        if form.is_valid():
            new_entry= form.save(commit=False)
            new_entry.topic = topic
            new_entry.owner = request.user
            new_entry.save()
            return HttpResponseRedirect(reverse('learn_app:topic',args=[topic_id]))
    context={'topic':topic,'form':form}
    return render(request,'learn_app/new_entry.html',context)

@ratelimit
@login_required 
def edit_entry(request,entry_id):
    """编辑条目"""
    entry = get_object_or_404(Entry, id=entry_id)
    topic = entry.topic
    if topic.owner != request.user:
        raise Http404
    if request.method != 'POST':
        form =EntryForm(instance=entry)
    else:
        form =EntryForm(instance=entry,data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('learn_app:topic',args=[topic.id]))
    context = {'entry': entry,'form': form}
    return render(request,'learn_app/edit_entry.html', context)

@ratelimit
@login_required 
def edit_topic(request,topic_id):
    """编辑主题"""
    topic = get_object_or_404(Topic,id=topic_id)
    if topic.owner != request.user:
        raise Http404
    if request.method != 'POST':
        form = TopicForm(instance=topic)
    else:
        form = TopicForm(instance=topic,data=request.POST)
        if form.is_valid():
            form.save()
            return redirect('learn_app:topics')
    context = {'form':form,}
    return render(request,'learn_app/edit_topic.html',context)

@ratelimit
@login_required 
def del_topic(request,topic_id):
    """删除主题"""
    topic = get_object_or_404(Topic, id=topic_id, owner=request.user)
    if request.method == 'POST':
        topic.delete() 
        messages.success(request, f"主题 '{topic.text}' 已成功删除！")
        return redirect('learn_app:topics')
    return render(request, 'learn_app/del_topic.html', {'topic': topic})

@ratelimit
@login_required 
def del_entry(request,entry_id):
    """删除条目"""
    entry = get_object_or_404(Entry,id=entry_id,topic__owner=request.user)#双下划线跨表查询
    topic=entry.topic
    if request.method == 'POST':
        entry.delete()
        entry_text=entry.text or ""
        entry_preview = entry.text[:50]+('...' if len(entry.text) > 50 else '')
        messages.success(request,f"条目'{entry_preview}'已成功删除!")
        return redirect('learn_app:topic',topic_id=topic.id)
    return render(request,'learn_app/del_entry.html',{'entry':entry,'topic':topic})

@login_required
def toggle_public(request,topic_id):
    """修改主题公开状态"""
    topic = get_object_or_404(Topic, id=topic_id)
    if request.user.is_authenticated and request.user == topic.owner:
        if request.method == 'POST':
            topic.public = not topic.public
            topic.save()
            return redirect('learn_app:topics')
        else:
            return HttpResponse("无权限修改此主题", status=403)
class SendFriendRequestView(APIView):
    permission_classes = [IsAuthenticated]
    def post(self,request):
        to_user_id = request.data.get('to_user_id')
        if not to_user_id:
            return Response({'error':'缺少目标用户ID(to_user_id)'},status=status.HTTP_400_BAD_REQUEST)
        to_user = get_object_or_404(User,id=to_user_id)
        existing_request = Friendship.objects.filter(from_user=request.user,to_user=to_user,status__in=['pending','accepted']).exists()
        if existing_request:
            return Response({'error':'无法重复发送请求(已发送或已是好友)'},status=status.HTTP_400_BAD_REQUEST)
        friendship = Friendship.objects.create(from_user=request.user,to_user=to_user)
        serializer = FriendshipSerializer(friendship)
class HandleFriendRequest(APIView):
    def post(self, request):
        request_id = request.data.get('request_id')
        action = request.data.get('action') 
        friend_request = get_object_or_404(Friendship, id=request_id, to_user=request.user)  
        
        if action == 'accept':
            friend_request.status = 'accepted'
            friend_request.save()
            return Response({'message': '已添加好友'})
        elif action == 'reject':
            friend_request.status = 'rejected'
            friend_request.save()  # 或直接删除：friend_request.delete()
            return Response({'message': '已拒绝请求'})